package com.hula.onion.book.server.spider.platforms.weidaiwang;

import com.alibaba.fastjson.JSONObject;
import com.hula.onion.book.server.common.CommonResponse;
import com.hula.onion.book.server.common.SpiderCommon;
import com.hula.onion.book.server.config.ResponseStatusEnum;
import com.hula.onion.book.server.utils.DateUtils;
import com.hula.onion.book.server.utils.HttpUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.impl.client.BasicCookieStore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * Description:
 * Create Date:2018/1/17 19:33
 *
 * @author shan
 * @version 1.0
 */
@Component("weiDaiWangSpider")
public class WeiDaiWangSpider extends SpiderCommon {
    /**
     * 登录URL
     */
    private static final String LOGIN_URL =
            "https://www.weidai.com.cn/login/v2/login?_api=login.loginIn&_mock=false&_stamp=";
    /**
     * 获取账户信息URL
     */
    private static final String GET_ACCOUNT_INFO_URL = "https://www.weidai.com.cn/account/accountInfo.html";

    @Autowired
    private WeiDaiWangSpiderHelper niWoDaiSpiderHelper;

    /**
     * 执行爬取操作
     */
    @Override
    public CommonResponse execute() {

        CommonResponse commonResponse = new CommonResponse(ResponseStatusEnum.FAIL);
        //设置该线程请求的线程上下文
        HttpClientContext httpContext = HttpClientContext.create();
        BasicCookieStore cookieStore = new BasicCookieStore();
        httpContext.setCookieStore(cookieStore);
        //1.1 组装模拟登陆参数
        try {
            Map<String, Object> params =
                    niWoDaiSpiderHelper.installRequestParams(loginForm);

            //1.2 模拟登陆
            String responseStr = HttpUtils.post(LOGIN_URL + DateUtils.getCurrentMillisecond(), params, httpContext);
            WeiDaiWangResponseEntity responseEntity = JSONObject.parseObject(responseStr, WeiDaiWangResponseEntity.class);

            logger.info("[weiDaiWangSpider] Http response result:{}", responseEntity.toString());

            if ("100".equals(responseEntity.getCode())) {
                //2.1 爬取用户详细信息
                String result = HttpUtils.get(GET_ACCOUNT_INFO_URL, httpContext);
                logger.info("[weiDaiWangSpider] Http response account result:{}", result);
                //2.2 解析JSON
                String accountBalance = niWoDaiSpiderHelper.parseAccountBalance(result);

                commonResponse = new CommonResponse(ResponseStatusEnum.SUCCESS);
                commonResponse.setData(accountBalance);

            } else {
                commonResponse.setMsg(responseEntity.getMessage());
                commonResponse.setCode(responseEntity.getCode());
            }

        } catch (Exception e) {
            logger.error("[weiDaiWangSpider] Install request params error!");
        }

        return commonResponse;
    }
}
